package top.lyc829.zzl_android.ui.team.add_team;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.lifecycle.ViewModelProvider;
import androidx.recyclerview.widget.GridLayoutManager;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.PagerSnapHelper;
import androidx.recyclerview.widget.RecyclerView;

import android.app.Activity;
import android.content.Intent;
import android.content.pm.ActivityInfo;
import android.net.Uri;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.ImageView;

import com.bumptech.glide.Glide;
import com.bumptech.glide.util.Util;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.chad.library.adapter.base.listener.OnItemChildClickListener;
import com.chad.library.adapter.base.listener.OnLoadMoreListener;
import com.google.android.material.bottomsheet.BottomSheetDialog;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.jeremyliao.liveeventbus.LiveEventBus;
import com.luck.picture.lib.PictureSelector;
import com.luck.picture.lib.config.PictureConfig;
import com.luck.picture.lib.config.PictureMimeType;
import com.luck.picture.lib.entity.LocalMedia;
import com.luck.picture.lib.listener.OnResultCallbackListener;
import com.xuexiang.xui.widget.dialog.materialdialog.DialogAction;
import com.xuexiang.xui.widget.dialog.materialdialog.MaterialDialog;
import com.xuexiang.xui.widget.picker.XSeekBar;
import com.xuexiang.xui.widget.picker.widget.TimePickerView;
import com.xuexiang.xui.widget.picker.widget.builder.TimePickerBuilder;
import com.xuexiang.xui.widget.picker.widget.utils.ChinaDateUtils;
import com.xuexiang.xutil.data.DateUtils;

import java.io.File;
import java.io.IOException;
import java.lang.ref.WeakReference;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import okhttp3.Response;
import top.lyc829.zzl_android.R;
import top.lyc829.zzl_android.databinding.ActivityAddDynamicBinding;
import top.lyc829.zzl_android.databinding.ActivityAddTeamBinding;
import top.lyc829.zzl_android.logic.adapter.GridImageAdapter;
import top.lyc829.zzl_android.logic.bean.ActivityBean;
import top.lyc829.zzl_android.logic.bean.BaseBean;
import top.lyc829.zzl_android.logic.bean.ResultBean;
import top.lyc829.zzl_android.logic.network.Network;
import top.lyc829.zzl_android.logic.util.GlideEngine;
import top.lyc829.zzl_android.logic.util.HttpUtil;
import top.lyc829.zzl_android.logic.util.PageInfo;
import top.lyc829.zzl_android.logic.util.Url;
import top.lyc829.zzl_android.logic.util.Utils;
import top.lyc829.zzl_android.logic.util.gson.JsonUtilNew;
import top.lyc829.zzl_android.ui.add.AddDynamicActivity;
import top.lyc829.zzl_android.ui.base_detail.SonCommentsAdapter;
import top.lyc829.zzl_android.ui.custom_view.seach.KylinSearchView;
import top.lyc829.zzl_android.ui.index.RecyclerViewAdapter;
import top.lyc829.zzl_android.ui.main.MainViewModel;

public class AddTeamActivity extends AppCompatActivity {

    ActivityAddTeamBinding binding;
    AddTeamViewModel mViewModel;

    private TimePickerView mStartDatePicker, mEndDatePicker;
    AddActivityAdapter adapter;

    BottomSheetDialog dialog;
    RecyclerViewAdapter bottomAdapter;

    PageInfo basePage;

    File teamImg = null;

    // 当前选择的卡片位置
    int choosePosition = -1;

    private String searchName = "";


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        binding = ActivityAddTeamBinding.inflate(getLayoutInflater());
        setContentView(binding.getRoot());

        mViewModel = new ViewModelProvider(this).get(AddTeamViewModel.class);
        basePage = new PageInfo();

        binding.addTeamType.setSelectedIndex(0);
        initRecycler();

        dialog = new BottomSheetDialog(this);
        bottomAdapter = new RecyclerViewAdapter();


        clickListener();
        observer();
    }

    private void observer() {
        mViewModel.getBaseListLiveData().observe(this, baseBeans -> {
            Utils.Sout(String.valueOf(baseBeans.size()));

            if (dialog != null && dialog.isShowing()) {
                if (basePage.isFirstPage()) {
                    bottomAdapter.setList(baseBeans);
                } else {
                    bottomAdapter.addData(baseBeans);
                }

                if (baseBeans.size() < PageInfo.MAX_ITEM) {
                    bottomAdapter.getLoadMoreModule().loadMoreEnd();
                } else {
                    basePage.nextPage();
                    // 加载完成，等待下一次加载
                    bottomAdapter.getLoadMoreModule().loadMoreComplete();
                }
            }
        });
    }

    /**
     * 初始化Snap
     */
    private void initRecycler() {
        LinearLayoutManager linearLayoutManager = new LinearLayoutManager(this);
        linearLayoutManager.setOrientation(LinearLayoutManager.HORIZONTAL);
        binding.addTeamActivityRecycler.setLayoutManager(linearLayoutManager);
        PagerSnapHelper snapHelper = new PagerSnapHelper();
        snapHelper.attachToRecyclerView(binding.addTeamActivityRecycler);
        adapter = new AddActivityAdapter();
        binding.addTeamActivityRecycler.setAdapter(adapter);

        //binding.addTeamActivityRecycler.getRecycledViewPool().setMaxRecycledViews(viewType,0);

        List<ActivityBean> list = new ArrayList<>();
        ActivityBean activityBean = new ActivityBean();
//        activityBean.setBeginDate(String.valueOf(DateUtils.getNowMills()));
//        activityBean.setEndDate(String.valueOf(DateUtils.string2Millis(DateUtils.nDaysAfterToday(1, false), DateUtils.yyyyMMdd.get())));
        list.add(activityBean);
        adapter.setList(list);

    }


    private void clickListener() {
        binding.mTitleBarAddTeam.setLeftClickListener(v -> finish());

        binding.addTeamHeaderImg.setOnClickListener(v -> {
            chooseHeadImage();
        });

        binding.addTeamType.setOnItemSelectedListener((spinner, position, id, item) -> {
            Utils.showToast(String.valueOf(position));
        });

        binding.btnAddActivity.setOnClickListener(v -> {
            if (adapter.getData().size() >= 10) {
                Utils.showToast("最多添加10个活动");
                return;
            }
            ActivityBean activityBean = new ActivityBean();
//            activityBean.setBeginDate(String.valueOf(DateUtils.getNowMills()));
//            activityBean.setEndDate(String.valueOf(DateUtils.string2Millis(DateUtils.nDaysAfterToday(1, false), DateUtils.yyyyMMdd.get())));
            adapter.addData(activityBean);
            // 添加活动后平滑滚动
            binding.addTeamActivityRecycler.smoothScrollToPosition(adapter.getData().size() - 1);
        });

        adapter.setOnItemLongClickListener((adapter1, view, position) -> {
            // 长按删除
            if (adapter.getData().size() == 1) {
//                Utils.showToast("最少保持一个活动");
                return false;
            }
            new MaterialDialog.Builder(this)
                    .content("是否删除该活动?")
                    .positiveText("是")
                    .negativeText("否")
                    .onPositive((dialog, which) -> {
                        adapter.removeAt(position);
                    })
                    .show();
            return false;
        });

        adapter.addChildClickViewIds(R.id.btn_set_base, R.id.tv_start_date, R.id.tv_end_date);
        adapter.setOnItemChildClickListener((adapter, view, position) -> {
            choosePosition = position;
            switch (view.getId()) {
                case R.id.btn_set_base:
                    // 跳转到选择基地
                    basePage.reset();
                    chooseBase();
                    break;
                case R.id.tv_start_date:
                    chooseStartDate(position);
                    break;
                case R.id.tv_end_date:
                    chooseEndtDate(position);
                    break;
                default:
                    break;
            }
        });


        binding.btnTeamApply.setOnClickListener(v -> {
            createTeam();

        });
    }

    private void createTeam() {
        String name = binding.addTeamName.getText().toString().trim();
        int type = binding.addTeamType.getSelectedIndex();
        int userId = Utils.getUserId();
        List<ActivityBean> activities = adapter.getData();
        String introduction = binding.addTeamIntroduction.getText().toString().trim();

        if (Utils.isStringEmpty(name)) {
            Utils.showToast("团队名不能为空");
            return;
        } else if (Utils.isStringEmpty(introduction)) {
            Utils.showToast("团队简介不能为空");
            return;
        } else if (teamImg == null) {
            Utils.showToast("团队图片不能为空");
            return;
        }

        Map<String, String> jsonMap = new HashMap<>();
        jsonMap.put("team_name", name);
        jsonMap.put("host_user_id", String.valueOf(userId));
        jsonMap.put("team_type", String.valueOf(type));
        jsonMap.put("team_describe", introduction);

        HttpUtil.getInstance(this)
                .sendSingleFileWithParams(Url.CREATE_TEAM, jsonMap, teamImg, "team_img", new HttpUtil.MyCallback() {
                    @Override
                    public void success(Response res) throws IOException {
                        String resStr = res.body().string();
                        ResultBean<Integer> resultBean = JsonUtilNew.fromJsonObject(resStr, Integer.class);
                        if (resultBean.getCode().equals(200)) {
                            runOnUiThread(() -> {
                                uploadActivities(resultBean.getData());
                            });

                        } else {
                            failed(new IOException(resultBean.getMsg()));
                        }
                    }

                    @Override
                    public void failed(IOException e) {
                        runOnUiThread(() -> {
                            Utils.showToast("创建失败");
                            Utils.SoutErr(e.getMessage());
                        });

                    }
                });
    }

    /**
     * 上传活动
     * @param teamId 团队id
     */
    private void uploadActivities(Integer teamId) {

        if (!checkActivity()) {
            Utils.SoutErr("活动条件不符合");
            quitTeam(teamId);
            return;
        }
        Network.addActivities(Utils.getUserId(), teamId, adapter.getData(), new HttpUtil.MyCallback() {
            @Override
            public void success(Response res) throws IOException {
                String resStr = res.body().string();
                ResultBean<List<Void>> resultBean = JsonUtilNew.fromJsonArray(resStr, Void.class);
                if (resultBean.getCode().equals(200)) {
                    runOnUiThread(() -> {
                        Utils.showToast("创建成功");
                        LiveEventBus
                                .get("team_change")
                                .post(1);
                        finish();
                    });
                } else {
                    failed(new IOException(resultBean.getMsg()));
                }
            }

            @Override
            public void failed(IOException e) {
                runOnUiThread(() -> {
                    Utils.showToast("创建失败");
                    Utils.SoutErr(e.getMessage());
                    quitTeam(teamId);
                });

            }
        });
    }

    private boolean checkActivity() {
        for (int i = 0; i < adapter.getData().size(); i++) {
            ActivityBean activityBean = adapter.getItem(i);

            Utils.Sout(activityBean.toString());

            if (activityBean.getBeginDate() == null) {
                activityBean.setBeginDate(String.valueOf(DateUtils.date2Millis(DateUtils.getStartOfDay(DateUtils.getNowDate()))));
            }
            if (activityBean.getEndDate() == null) {
                activityBean.setEndDate(String.valueOf(DateUtils.date2Millis(DateUtils.getEndOfDay(DateUtils.getNowDate()))));
            }

            if (Utils.isStringEmpty(activityBean.getName())) {
                Utils.showToast("活动" + (i + 1) + "名称不能为空");
                return false;
            } else if (activityBean.getBaseId() == null || Utils.isStringEmpty(activityBean.getBaseName())) {
                Utils.showToast("活动" + (i + 1) + "基地未选择");
                return false;
            } else if (activityBean.getNumber() == null) {
                Utils.showToast("活动" + (i + 1) + "人数不能未空");
                return false;
            } else if (Long.parseLong(activityBean.getBeginDate()) >= Long.parseLong(activityBean.getEndDate())) {
                Utils.showToast("活动" + (i + 1) + "开始日期不能大于结束日期");
                return false;
            }
        }

        return true;
    }

    private void quitTeam(Integer teamId) {
        Network.quitTeam(teamId, Utils.getUserId(), new HttpUtil.MyCallback() {
            @Override
            public void success(Response res) throws IOException {
                ResultBean<Void> resultBean = JsonUtilNew
                        .fromJsonObject(res.body().string(), Void.class);

                if (resultBean.getCode().equals(200)) {
                } else {
                    failed(new IOException(resultBean.getMsg()));
                }
            }

            @Override
            public void failed(IOException e) {
                Utils.Sout(e.getMessage());
            }
        });
    }

    private void chooseEndtDate(int position) {
        ActivityBean oldActivity = adapter.getData().get(position);

        Calendar startCalendar = Calendar.getInstance();
        startCalendar.setTimeInMillis(DateUtils.getNowMills());

        Calendar endCalendar = Calendar.getInstance();
        endCalendar.setTime(DateUtils.nMonthsAfterToday(24));

        // XToastUtils.toast()
        new TimePickerBuilder(this, (date, v) -> {
            oldActivity.setEndDate(String.valueOf(DateUtils.date2Millis(DateUtils.getEndOfDay(date))));
//            if (oldActivity.getBeginDate() == null || Long.parseLong(oldActivity.getEndDate()) < Long.parseLong(oldActivity.getBeginDate())) {
//                oldActivity.setBeginDate(String.valueOf(DateUtils.date2Millis(DateUtils.getStartOfDay(date))));
//            }
            adapter.setData(position, oldActivity);
        })
                .setTitleText("结束日期")
                .setRangDate(startCalendar, endCalendar)
                .build()
                .show();
    }

    private void chooseStartDate(int position) {

        ActivityBean oldActivity = adapter.getData().get(position);

        Calendar startCalendar = Calendar.getInstance();
        startCalendar.setTimeInMillis(DateUtils.getNowMills());

        Calendar endCalendar = Calendar.getInstance();
        endCalendar.setTime(DateUtils.nMonthsAfterToday(24));

        // XToastUtils.toast()
        new TimePickerBuilder(this, (date, v) -> {
            Utils.showToast(DateUtils.date2String(date, DateUtils.yyyyMMdd.get()));
            oldActivity.setBeginDate(String.valueOf(DateUtils.date2Millis(DateUtils.getStartOfDay(date))));
//            if (oldActivity.getEndDate() == null || Long.parseLong(oldActivity.getEndDate()) < Long.parseLong(oldActivity.getBeginDate())) {
//                oldActivity.setEndDate(String.valueOf(DateUtils.date2Millis(DateUtils.getEndOfDay(date))));
//            }
            adapter.setData(position, oldActivity);
        })
                .setTitleText("开始日期")
                .setRangDate(startCalendar, endCalendar)
                .build()
                .show();

    }


    private void chooseBase() {
        showBottomDialog();

        mViewModel.getBasesInCreateTeam("", basePage.getPage());

        // 底部选择一个基地后返回，活动卡片显示基地名称
        bottomAdapter.setOnItemClickListener((adapter1, view, position) -> {
            BaseBean baseBean = ((BaseBean)adapter1.getData().get(position));
            ActivityBean oldActivity = adapter.getData().get(choosePosition);
            oldActivity.setBaseId(baseBean.getId());
            oldActivity.setBaseName(baseBean.getTitle());
            adapter.setData(choosePosition, oldActivity);
            Utils.Sout(oldActivity.toString());

            dialog.cancel();
        });

    }

    /**
     * 弹出底部弹窗
     */
    private void showBottomDialog() {

        View view = LayoutInflater.from(this).inflate(R.layout.bottom_sheet_layout_choose_base, null);
        RecyclerView recyclerView = view.findViewById(R.id.search_team_recyclerview);

        GridLayoutManager layoutManager = new GridLayoutManager(this, 2);
        recyclerView.setLayoutManager(layoutManager);


        recyclerView.setAdapter(bottomAdapter);
        bottomAdapter.setList(null);


        view.findViewById(R.id.btn_search_base).setOnClickListener(v -> {
            String searchContent = ((KylinSearchView)view.findViewById(R.id.search_base)).getSearchContent();
            if (Utils.isStringEmpty(((KylinSearchView)view.findViewById(R.id.search_base)).getSearchContent())) {
                searchContent = "";
            }
            basePage.reset();
            searchName = searchContent;
            mViewModel.getBasesInCreateTeam(searchContent, basePage.getPage());

        });

        dialog.setContentView(view);
        dialog.setCancelable(true);
        dialog.setCanceledOnTouchOutside(true);
        dialog.show();

        // 上拉加载
        initSonLoadMore();
    }

    /**
     * 上拉加载更多
     */
    private void initSonLoadMore() {
        bottomAdapter.getLoadMoreModule().setOnLoadMoreListener(new OnLoadMoreListener() {
            @Override
            public void onLoadMore() {
                sonRequest();
            }
        });
        bottomAdapter.getLoadMoreModule().setAutoLoadMore(true);
        //当自动加载开启，同时数据不满一屏时，是否继续执行自动加载更多(默认为true)
        bottomAdapter.getLoadMoreModule().setEnableLoadMoreIfNotFullPage(false);
    }

    private void sonRequest() {
        mViewModel.getBasesInCreateTeam(searchName, basePage.getPage());
    }


    /**
     * 选择题图
     */
    public void chooseHeadImage() {
        PictureSelector.create(this)
                .openGallery(PictureMimeType.ofImage())
                .imageEngine(GlideEngine.createGlideEngine())// 外部传入图片加载引擎，必传项
                .isMaxSelectEnabledMask(true)
                .selectionMode(PictureConfig.SINGLE)
                .isReturnEmpty(false)// 未选择数据时点击按钮是否可以返回
                .synOrAsy(false)
                .isEnableCrop(true)// 是否裁剪
                .withAspectRatio(16, 9)
                .freeStyleCropEnabled(true)
                .isCompress(true)
                .isAndroidQTransform(true)
                .showCropFrame(true)// 是否显示裁剪矩形边框 圆形裁剪时建议设为false
                .showCropGrid(true)
                .forResult(new OnResultCallbackListener<LocalMedia>() {
                    @Override
                    public void onResult(List<LocalMedia> result) {
                        teamImg = new File(result.get(0).getCompressPath());
                        Glide.with(AddTeamActivity.this)
                                .load(result.get(0).getCutPath())
                                .into((ImageView) findViewById(R.id.add_team_header_img));
                    }

                    @Override
                    public void onCancel() {
                        // 取消
                    }
                });
    }


}